package com.hertz.appr.service;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;
import org.apache.sanselan.ImageFormat;
import org.apache.sanselan.Sanselan;
import org.w3c.dom.Document;
import org.xhtmlrenderer.extend.FontResolver;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;
import org.xhtmlrenderer.simple.Graphics2DRenderer;
import org.xhtmlrenderer.simple.ImageRenderer;
import org.xhtmlrenderer.simple.XHTMLPanel;
import org.xhtmlrenderer.swing.BasicPanel;

import com.hertz.appr.util.Configuration;
import com.lowagie.text.pdf.BaseFont;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class ImageService {
	
	private Logger log = Logger.getLogger(ImageService.class);
	private String baseHtmlPath;
	private String basePdfPath;
	private String baseImgPath;
	private final String htmlEx = ".html";
	private final String pdfEx = ".pdf";
	private final String imgFx = ".jpg";
	private String fontPath;
	private String fontPathLinux;
	
	public ImageService(){
		baseHtmlPath = Configuration.getProperty("html.path");
		baseImgPath = Configuration.getProperty("img.path");
		basePdfPath = Configuration.getProperty("pdf.path");
		fontPath = Configuration.getProperty("font.path");
		fontPathLinux = Configuration.getProperty("linux.font.path");
	}
	
	public boolean html2Img(Long aid){
		boolean result = false;
		try {
			String inputFile = baseHtmlPath + aid + htmlEx;  
			log.debug("inputFile=" + inputFile);
			File file = new File(inputFile);
			if (file.exists()) {
				
				BufferedImage img = Graphics2DRenderer.renderToImageAutoSize(file.toURI().toURL().toExternalForm(), 1024);
//				BufferedImage img = ImageRenderer.renderImageToOutput(file.toURI().toURL(), fsw, path, width)
				ImageFormat format = ImageFormat.IMAGE_FORMAT_BMP;
				File tempOutFile = new File(baseImgPath + aid + "_.bmp");
		        Sanselan.writeImage(img, tempOutFile, format, null);
				
				BufferedImage srcImg = ImageIO.read(tempOutFile);
				
				FileOutputStream out = new FileOutputStream(baseImgPath + aid + imgFx); // 输出到文件流
		        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		        JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(srcImg);
		        param2.setQuality(1f, false);// 1f是提高生成的图片质量
//		        param2.
		        encoder.setJPEGEncodeParam(param2);
		        encoder.encode(srcImg); // JPEG编码
		        out.close();
				
				
//				ImageIO.write(srcImg, "JPEG", new File(baseImgPath + aid + imgFx));
				tempOutFile.deleteOnExit();
				log.debug("delete " + tempOutFile.getName()); 
				result = true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return result;
//		
//		
		// maybe it's a file
		
	}
	
	public boolean html2PDF(Long aid){
		boolean result = false;
		try {
			String inputFile = baseHtmlPath + aid + htmlEx;  
			log.debug("inputFile=" + inputFile);
	        String url = new File(inputFile).toURI().toURL().toString();  
	        String outputFile = basePdfPath + aid + pdfEx;  
	        OutputStream os = new FileOutputStream(outputFile);  
	        ITextRenderer renderer = new ITextRenderer();  
	        ImageRenderer imageRender = new ImageRenderer();
	        renderer.setDocument(url);  
	  
	        // 解决中文支持问题  
	        ITextFontResolver fontResolver = renderer.getFontResolver(); 
	        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
	        	log.debug("windows fontPath=" + fontPath);
	        	fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  
	        } else {
	        	fontResolver.addFont(fontPathLinux, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  
	        }
	  
	        // 解决图片的相对路径问题  
	        renderer.getSharedContext().setBaseURL("file:/" + basePdfPath);  
	          
	        renderer.layout();  
	        renderer.createPDF(os);  
	          
	        os.close();  
	        result = true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return result;
	}
	
	public boolean pdf2Img(Long aid){
		boolean result = false;
		try {
			File file = new File(basePdfPath + aid + pdfEx);
	        RandomAccessFile raf = new RandomAccessFile(file, "r");
	        FileChannel channel = raf.getChannel();
	        MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
	        PDFFile pdffile = new PDFFile(buf);
	        Graphics2D graphics = null;
	        BufferedImage tag = new BufferedImage(595, 842 * pdffile.getNumPages(),BufferedImage.TYPE_INT_RGB);
	        graphics = (Graphics2D)tag.getGraphics();
//	        .setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
	        int height = 0;
	        for (int i = 1; i <= pdffile.getNumPages(); i++) {
	            PDFPage page = pdffile.getPage(i);
	            Rectangle rect = new Rectangle(0, 0, ((int) page.getBBox().getWidth()), ((int) page.getBBox().getHeight()));
	            Image img = page.getImage(rect.width, rect.height, rect,
	                    null, // null for the ImageObserver
	                    true, // fill background with white
	                    true // block until drawing is done
	                    );
	            graphics.drawImage(img, 0, height, rect.width, rect.height, null);
	            tag.flush();
	            height += 842;
	        }
	        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	        FileOutputStream out = new FileOutputStream(baseImgPath + aid + imgFx); // 输出到文件流
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
	        JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(tag);
	        param2.setQuality(1f, false);// 1f是提高生成的图片质量
//	        param2.
	        encoder.setJPEGEncodeParam(param2);
	        encoder.encode(tag); // JPEG编码
	        out.close();
	        channel.close();
	        raf.close();
	        result = true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		
		return result;
	}
	
	public File getImgFile(Long aid){
		String path = baseImgPath + aid + imgFx;
		File file = new File(path);
		if(file.exists() && file.isFile()){
			return file;
		}else{
			return null;
		}
	}

	public String getBasePdfPath() {
		return basePdfPath;
	}

	public void setBasePdfPath(String basePdfPath) {
		this.basePdfPath = basePdfPath;
	}

	public String getBaseImgPath() {
		return baseImgPath;
	}

	public void setBaseImgPath(String baseImgPath) {
		this.baseImgPath = baseImgPath;
	}

	public String getBaseHtmlPath() {
		return baseHtmlPath;
	}

	public void setBaseHtmlPath(String baseHtmlPath) {
		this.baseHtmlPath = baseHtmlPath;
	}

	public String getFontPath() {
		return fontPath;
	}

	public void setFontPath(String fontPath) {
		this.fontPath = fontPath;
	}

	public String getFontPathLinux() {
		return fontPathLinux;
	}

	public void setFontPathLinux(String fontPathLinux) {
		this.fontPathLinux = fontPathLinux;
	}
	
}
